package com.cqhilink.api.common.utils.security.aes;



import com.cqhilink.api.common.utils.security.base64.Base64Encod;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

/**
 * AES加密解密
 * Created by wangzhen on 2016/6/6.
 */
public class AESEncAndDec {
    /**
     * 加密
     *
     * @param data 加密密的内容数据
     * @param key  加密密钥
     * @return
     */
    public static String encryptAES(String data, String key) throws Exception {
        byte[] source = data.getBytes();
        SecretKey secretKey = CreateAESKey.loadKeyAES(key);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(source);
        String byte2base64 = Base64Encod.byte2base64(bytes);
        return byte2base64;
    }

    /**
     * 解密
     *
     * @param data 解密密的内容数据
     * @param key  解密密钥
     * @return
     * @throws Exception
     */
    public static String decryptAES(String data, String key) throws Exception {
        byte[] source = Base64Encod.base642byte(data);
        SecretKey secretKey = CreateAESKey.loadKeyAES(key);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(source);
        String decryptAES = new String(bytes, "UTF-8");
        return decryptAES;
    }
}
